package com.bjpowerrnode.javase.random;

import java.util.Arrays;
import java.util.Random;

/*
编写程序生成5个不重复的随机数，重复的话重新生成，最终生成的5个随机数放到数组中。
 */
public class RansomTest02 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            int retValue = random.nextInt();
            sb.append(retValue+",");
        }
        String str = sb.toString();
        System.out.println("str="+str);
       /* char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            System.out.println(ch[i]);
        }*/
        String[] strings = str.split(",");
        System.out.println(strings);
        for (int i = 0; i < strings.length; i++) {
            System.out.println(strings[i]);
        }

        int[] ints = new int[5];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = random.nextInt();
        }
        System.out.println("+++++++++++++++++++++++");
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);
        }

        int[] arr = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = -1;
        }
        //循环生成随机数
        System.out.println("-------------");
        int index = 0;
        while(index < arr.length){
            //生成随机数
            int number = random.nextInt(5);
            boolean temp = true;
/*            //判断arr数组中有没number
            for (int i = 0; i < arr.length; i++) {
                if(number == arr[i]){
                    temp = false;
                }
            }*/
            if (contans(arr,number)){
                arr[index++] = number;
            }
            System.out.println(index);
        }
        System.out.println("==============================");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }

    //单独辨析一个方法用来判断数组中是否有某个元素
    public static boolean contans(int[] arr,int key){
        for (int i = 0; i <arr.length ; i++) {
            if(arr[i] == key) return false;
        }
        return true;

        //以下方案存在bug
/*        //对数组进行升序

        Arrays.sort(arr);
        return  Arrays.binarySearch(arr,key) >= 0;*/

    }
}
